//
//  TDRealNameCertificationTableViewController.m
//  TFB
//
//  Created by yull on 15/8/15.
//  Copyright (c) 2015年 TD. All rights reserved.
//

#import "TDRealNameCertificationTableViewController.h"
#import "TDRealNamePicView.h"
#import "TDSelectLocationTableViewController.h"
#import <objc/runtime.h>
#import "TDCommonData.h"

#define HANDHELD 201
#define FRONT    202
#define BACK     203

static NSString *rowKey;
@implementation UITextField (TableView)

- (void)setIndexPath:(NSIndexPath *)indexPath
{
    objc_setAssociatedObject(self, &rowKey, indexPath, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSIndexPath *)indexPath
{
    return objc_getAssociatedObject(self, &rowKey);
}

@end

@interface TDRealNameCertificationTableViewController () <UINavigationControllerDelegate, UIImagePickerControllerDelegate, UITextFieldDelegate>

@property (nonatomic, assign) NSInteger takeImgTag;
@property (nonatomic, strong) TDRealNamePicView *headerView;

@property (nonatomic, strong) NSArray *leftArray;
@property (nonatomic, strong) NSArray *placeholderArray;

@property (nonatomic, strong) NSString *activeCode;
@property (nonatomic, strong) NSString *sendHandheldImage;
@property (nonatomic, strong) NSString *sendFrontImage;
@property (nonatomic, strong) NSString *sendBackImage;
@property (nonatomic, strong) TDProvince *province;
@property (nonatomic, strong) TDCity *city;
@property (nonatomic, strong) TDArea *area;
@property (nonatomic, strong) NSString *certificateNo;
@property (nonatomic, strong) NSString *userEmail;
@property (nonatomic, strong) NSString *custName;

@end

@implementation TDRealNameCertificationTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    self.navigationItem.title = @"实名认证";
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    if ([APPNAME isEqualToString:@"吉米支付"]) {
        self.leftArray = @[@"姓名", @"身份证号", @"邮箱", @"开户城市"];
        self.placeholderArray = @[@"请输入身份证上的姓名", @"请输入身份证号", @"请输入邮箱", @"请点击选择（省 市/区）"];
    } else {
        self.leftArray = @[@"激活码", @"姓名", @"身份证号", @"邮箱", @"开户城市"];
        self.placeholderArray = @[@"请输入激活码", @"请输入身份证上的姓名", @"请输入身份证号", @"请输入邮箱", @"请点击选择（省 市/区）"];
    }
    
    
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 1, SVFS.width, 80)];
    UIButton *nextBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    nextBtn.frame = CGRectMake(10, 16, SVFS.width - 20, 44);
    [nextBtn setBackgroundImage:[UIImage imageNamed:@"bg_btn"] forState:0];
    [nextBtn setTitle:@"下一步" forState:0];
    [nextBtn setTitleColor:[UIColor whiteColor] forState:0];
    [nextBtn addTarget:self action:@selector(onClickNextBtn:) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:nextBtn];
    
    self.tableView.tableFooterView = footerView;
    
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    
    [self initData];
}

- (void)initData
{
    self.activeCode = [TDCommonData defaultInstance].rmActiveCode;
    self.certificateNo = [TDCommonData defaultInstance].rmCertificateNo;
    self.userEmail = [TDCommonData defaultInstance].rmUserEmail;
    self.custName = [TDCommonData defaultInstance].rmCustName;
    self.province = [TDCommonData defaultInstance].rmProvince;
    self.city = [TDCommonData defaultInstance].rmCity;
    self.area = [TDCommonData defaultInstance].rmArea;
}

- (void)onClickNextBtn:(id)sender
{
    if (!self.sendHandheldImage.length) {
        [self.navigationController.view makeToast:@"请拍摄手持身份证正面照" duration:2.0f position:@"center"];
        return;
    }
    
    if (!self.sendFrontImage.length) {
        [self.navigationController.view makeToast:@"请拍摄身份证正面照" duration:2.0f position:@"center"];
        return;
    }
    
    if (!self.sendBackImage.length) {
        [self.navigationController.view makeToast:@"请拍摄身份证反面照" duration:2.0f position:@"center"];
        return;
    }
    
    if (!self.activeCode.length && ![APPNAME isEqualToString:@"吉米支付"]) {
        [self.navigationController.view makeToast:@"请输入激活码" duration:2.0f position:@"center"];
        return;
    }
    
    if (!self.custName.length) {
        [self.navigationController.view makeToast:@"请输入身份证上的姓名" duration:2.0f position:@"center"];
        return;
    }
    
    if (![self isHanzi:self.custName]) {
        [self.navigationController.view makeToast:@"姓名请输入汉字" duration:2.0f position:@"center"];
        return;
    }
    
    if (!self.certificateNo.length) {
        [self.navigationController.view makeToast:@"请输入身份证号" duration:2.0f position:@"center"];
        return;
    }
    
    if (!self.province || !self.city || !self.area) {
        [self.navigationController.view makeToast:@"请选择开户城市" duration:2.0f position:@"center"];
        return;
    }
    
    if (!self.userEmail.length || [self.userEmail rangeOfString:@"@"].location == NSNotFound) {
        [self.navigationController.view makeToast:@"请输入含@的QQ邮箱或其他邮箱" duration:2.0f position:@"center"];
        return;
    }
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [TDHttpEngine requestForCertificationWithCardHandheld:self.sendHandheldImage
                                                cardFront:self.sendFrontImage
                                                 cardBack:self.sendBackImage
                                               activeCode:self.activeCode
                                                   custId:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_ID]
                                               custMobile:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_MOBILE]
                                                 custName:self.custName
                                          certificateType:@"01"
                                            certificateNo:self.certificateNo
                                                userEmail:self.userEmail
                                               provinceId:self.province.provId
                                                   cityId:self.city.cityId
                                                   areaId:self.area.areaId
                                                   payPwd:nil
                                                 complete:^(BOOL succeed, NSString *msg, NSString *cod) {
                                                     [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                                                     if (succeed) {
                                                         
                                                         [TDUser defaultUser].custStatus = @"1";
                                                         [self.navigationController.view makeToast:msg duration:2.0f position:@"center"];
                                                         [self performSelector:@selector(popToRoot) withObject:self afterDelay:2.0f];
                                                     } else {
                                                         [self.navigationController.view makeToast:msg duration:2.0f position:@"center"];
                                                     }
                                                 }];
}

- (BOOL)isHanzi:(NSString *)content
{
    for (int i = 0; i < content.length; i++) {
        unichar c = [content characterAtIndex:i];
        if (c >= 0x4E00 && c <= 0x9FA6)
        {
            continue;
        }
        
        return NO;
    }
    
    return YES;
}

- (void)popToRoot
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)getPhoto:(UIButton *)sender
{
    _takeImgTag = sender.tag;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.sourceType =UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:imagePicker animated:YES completion:nil];
    }
    else{
        [self.view makeToast:@"该设备没有摄像头" duration:2.0f position:@"center"];
    }
    
//    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
//    imagePicker.delegate = self;
//    imagePicker.sourceType =UIImagePickerControllerSourceTypePhotoLibrary;
//    [self presentViewController:imagePicker animated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSLog(@"照片信息--%@", info);
    [self dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];

    NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
    while (imageData.length > 200*1024) {
        image = [self scaleImage:image toScale:0.5];
        imageData = UIImageJPEGRepresentation(image, 0.5);
    }
    
    switch (_takeImgTag) {
        case HANDHELD:{
            [self.headerView.handHoldBtn setImage:nil forState:0];
            [self.headerView.handHoldBtn setBackgroundImage:image forState:0];
            _sendHandheldImage = [imageData base64EncodedString];
            [TDCommonData defaultInstance].rmHandHoldImage = image;
        }
            break;
        case FRONT:{
            [self.headerView.frontBtn setImage:nil forState:0];
            [self.headerView.frontBtn setBackgroundImage:image forState:0];
            _sendFrontImage = [imageData base64EncodedString];
            [TDCommonData defaultInstance].rmFrontImage = image;
        }
            break;
        case BACK:{
            [self.headerView.backBtn setImage:nil forState:0];
            [self.headerView.backBtn setBackgroundImage:image forState:0];
            _sendBackImage = [imageData base64EncodedString];
            [TDCommonData defaultInstance].rmBackImage = image;
        }
            break;
            
        default:
            break;
    }
}

//重新绘制图片的尺寸
-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    
    return scaledImage;
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    if (section == 0) {
        return 1;
    }
    
    return self.leftArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 320;
    }
    
    return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        static NSString *identifier = @"picIdentifier";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        
        if (nil == cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            TDRealNamePicView *view = [TDRealNamePicView instanceView];
            view.frame = CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height);
            [view.handHoldBtn addTarget:self action:@selector(getPhoto:) forControlEvents:UIControlEventTouchUpInside];
            [view.frontBtn addTarget:self action:@selector(getPhoto:) forControlEvents:UIControlEventTouchUpInside];
            [view.backBtn addTarget:self action:@selector(getPhoto:) forControlEvents:UIControlEventTouchUpInside];
            [cell.contentView addSubview:view];
            self.headerView = view;
        }
        
        if ([TDCommonData defaultInstance].rmHandHoldImage) {
            [self.headerView.handHoldBtn setImage:nil forState:0];
            [self.headerView.handHoldBtn setBackgroundImage:[TDCommonData defaultInstance].rmHandHoldImage forState:0];
            NSData *imageData = UIImageJPEGRepresentation([TDCommonData defaultInstance].rmHandHoldImage, 0.5);
            _sendHandheldImage = [imageData base64EncodedString];
        }
        
        if ([TDCommonData defaultInstance].rmFrontImage) {
            [self.headerView.frontBtn setImage:nil forState:0];
            [self.headerView.frontBtn setBackgroundImage:[TDCommonData defaultInstance].rmFrontImage forState:0];
            NSData *imageData = UIImageJPEGRepresentation([TDCommonData defaultInstance].rmFrontImage, 0.5);
            _sendFrontImage = [imageData base64EncodedString];
        }
        
        if ([TDCommonData defaultInstance].rmBackImage) {
            [self.headerView.backBtn setImage:nil forState:0];
            [self.headerView.backBtn setBackgroundImage:[TDCommonData defaultInstance].rmBackImage forState:0];
            NSData *imageData = UIImageJPEGRepresentation([TDCommonData defaultInstance].rmBackImage, 0.5);
            _sendBackImage = [imageData base64EncodedString];
        }
        
        return cell;
    }
    
    static NSString *identifier = @"realnameIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (nil == cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        UILabel *leftL = [[UILabel alloc] initWithFrame:CGRectMake(10, 2, 80, 40)];
        leftL.font = [UIFont systemFontOfSize:14];
        leftL.textColor = [UIColor grayColor];
        leftL.tag = 1001;
        [cell.contentView addSubview:leftL];
        
        UITextField *rightTF = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(leftL.frame), 2, SVFS.width - 10 - CGRectGetMaxX(leftL.frame), 40)];
        rightTF.font = [UIFont systemFontOfSize:17];
        rightTF.delegate = self;
        rightTF.tag = 1002;
        [cell.contentView addSubview:rightTF];
    }
    
    UILabel *leftL = (UILabel *)[cell.contentView viewWithTag:1001];
    leftL.text = self.leftArray[indexPath.row];
    
    UITextField *rightTF = (UITextField *)[cell.contentView viewWithTag:1002];
    rightTF.placeholder = self.placeholderArray[indexPath.row];
    rightTF.indexPath = indexPath;
    
    NSInteger isJimi = [APPNAME isEqualToString:@"吉米支付"] ? 1 : 0;
    
    if (indexPath.row == 4 - isJimi) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    if (indexPath.row == 0 - isJimi) {
        rightTF.text = self.activeCode;
    } else if (indexPath.row == 1 - isJimi) {
        rightTF.text = self.custName;
    } else if (indexPath.row == 2 - isJimi) {
        rightTF.text = self.certificateNo;
    } else if (indexPath.row == 3 - isJimi) {
        rightTF.text = self.userEmail;
    } else {
        if (self.province && self.city && self.area) {
            rightTF.text = [NSString stringWithFormat:@"%@ %@ %@", self.province.provName, self.city.cityName, self.area.areaName];
        } else {
            rightTF.text = @"";
        }
    }
    
    return cell;
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    NSInteger isJimi = [APPNAME isEqualToString:@"吉米支付"] ? 1 : 0;
    
    if (textField.indexPath.row != 4 - isJimi) {
        return YES;
    }
    
    [self.view endEditing:YES];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [TDHttpEngine requestForGetProvinceWithCustId:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_ID] custMobile:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_MOBILE] complete:^(BOOL succeed, NSString *msg, NSString *cod, NSArray *array) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        if (succeed) {
            TDSelectLocationTableViewController *controller = [[TDSelectLocationTableViewController alloc] initWithStyle:UITableViewStylePlain];
            controller.locations = array;
            controller.complete = ^(TDProvince *province, TDCity *city, TDArea *area) {
                self.province = province;
                self.city = city;
                self.area = area;
                
                [TDCommonData defaultInstance].rmProvince = province;
                [TDCommonData defaultInstance].rmCity = city;
                [TDCommonData defaultInstance].rmArea = area;
                
                [self.tableView reloadData];
            };
            
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:controller];
            nav.navigationBar.tintColor = [UIColor whiteColor];
            nav.navigationBar.barStyle = UIBarStyleBlack;
            [self presentViewController:nav animated:YES completion:nil];
        } else {
            [self.view makeToast:msg duration:2.0f position:@"center"];
        }
    }];
    
    return NO;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *content = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    NSInteger isJimi = [APPNAME isEqualToString:@"吉米支付"] ? 1 : 0;
    
    if (textField.indexPath.row == 0 - isJimi) {
        self.activeCode = content;
        [TDCommonData defaultInstance].rmActiveCode = content;
    } else if (textField.indexPath.row == 1 - isJimi) {
        self.custName = content;
        [TDCommonData defaultInstance].rmCustName = content;
    } else if (textField.indexPath.row == 2 - isJimi) {
        self.certificateNo = content;
        [TDCommonData defaultInstance].rmCertificateNo = content;
    } else if (textField.indexPath.row == 3 - isJimi) {
        self.userEmail = content;
        [TDCommonData defaultInstance].rmUserEmail = content;
    }
    
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    NSInteger isJimi = [APPNAME isEqualToString:@"吉米支付"] ? 1 : 0;
    
    if (textField.indexPath.row == 0 - isJimi) {
        self.activeCode = textField.text;
        [TDCommonData defaultInstance].rmActiveCode = textField.text;
    } else if (textField.indexPath.row == 1 - isJimi) {
        self.custName = textField.text;
        [TDCommonData defaultInstance].rmCustName = textField.text;
    } else if (textField.indexPath.row == 2 - isJimi) {
        self.certificateNo = textField.text;
        [TDCommonData defaultInstance].rmCertificateNo = textField.text;
    } else if (textField.indexPath.row == 3 - isJimi) {
        self.userEmail = textField.text;
        [TDCommonData defaultInstance].rmUserEmail = textField.text;
    }
    
    return YES;
}

@end
